package com.hxkj.config;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * Sql执行时间监控切面
 * <p>
 * Create by chenwei on 2018/10/11 9:55
 */
@Aspect
@Component
@Slf4j
public class MapperExecutionTimeAspect {

    @AfterReturning("execution(* com.hxkj.mapper.*Mapper.*(..))")
    public void logServiceAccess(JoinPoint joinPoint) {
        if (log.isDebugEnabled()) {
            log.info("Completed: " + joinPoint);
        }
    }


    @Pointcut("execution(* com.hxkj.mapper.*Mapper.*(..))")
    private void pointCutMethod() {
    }


    @Around("pointCutMethod()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long begin = System.nanoTime();
        Object proceed = proceedingJoinPoint.proceed();
        long end = System.nanoTime();

        long sqlExecutionTime = (end - begin) / 1000000;

        if (log.isDebugEnabled()) {
            log.debug("方法：{}，参数：{}，执行耗时：{}毫秒", proceedingJoinPoint.getSignature(),
                    Arrays.toString(proceedingJoinPoint.getArgs()), sqlExecutionTime);
        }
        return proceed;
    }

}
